<?php

namespace Frieza\Modules\Photo\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\AdminAccount\AdminAccountOperate;
use Doraemon\model\AdmNoteFeature;
use Doraemon\model\ContentSignExtend as PhotosExtend;
use Doraemon\model\Es\UserPortrait;
use Doraemon\model\Member;
use Doraemon\model\Photos as dbPhoto;
use Doraemon\model\Photos as DbPhotos;
use Doraemon\model\TopicActivity;
use Doraemon\service\Circle\PhotosCircle;
use Doraemon\service\DecorationTask\Read;
use Doraemon\service\Photos;
use Doraemon\service\Videos\Videos as sVideos;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Box;
use Illuminate\Http\Request;
use Doraemon\cache\FeaturePool as cFeaturePool;

class OperateFeatureController
{
    public function index(Request $request, Content $content)
    {
        $addTime = $request->get('add_time');
        $startTime = time() - 86400;
        $endTime = time();
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 20);
        $page = ($page - 1) * $pageSize;
        // 这种默认时间的写法会导致一种极端情况。 那就是随便选了一个N年之前的时间做开始时间，然后删除文本框的结束时间。
        // 这种情况下的时间区间就是  201x - current_time。
        if ($addTime['start']) {
            $startTime = strtotime($addTime['start']);
        }

        if ($addTime['end']) {
            $endTime = strtotime($addTime['end']);
        }

        if (!isset($addTime)) {
            $request->merge([
                'add_time' => [
                    'start' => date('Y-m-d H:i:s', strtotime("-1days")),
                    'end'   => date('Y-m-d H:i:s'),
                ]
            ]);
        }

        $result = cFeaturePool::getList($startTime, $endTime, $page, $pageSize);
        $total = cFeaturePool::getTotal($startTime, $endTime);
        $ids = array_keys($result);
//        $ids =['000d9tp00005c7mb','000d9tq00000098d','000d9tr00000098d'];
        $photos = Photos::getPhotos($ids); // 通过id获取图片信息
        // 获取装修日记
        $diaryList = $diaryIds = $circleList = $circleIds = [];
        foreach ($photos as $photo) {
            if ($photo['type'] == dbPhoto::TYPE_DIARY) {
                $diaryIds[] = $photo['id'];
            }
            if ($photo['type'] == dbPhoto::TYPE_CIRCLE) {
                $circleIds[] = $photo['id'];
            }
        }

        if ($diaryIds) {
            $diaryList = Read::getDiaryByDiaryIds($diaryIds);
        }
        if ($circleIds) {
            $circleList = PhotosCircle::selectPhotoCircle($circleIds);
        }

        //用户信息
        $uids = empty($photos) ? [] : array_column($photos, 'uid');
        $user_infos = Member::getUserInfoByIds($uids);
        $user_infos_regular = [];
        if ($user_infos && is_array($user_infos)) {
            foreach ($user_infos as $user_info) {
                $user_infos_regular[$user_info['uid']] = $user_info;
            }
        }

        //用户等级信息
        $user_levels = UserPortrait::getUserLevelByUIds(array_values(array_unique($uids)));
        //话题信息
        $topic_ids = empty($photos) ? [] : array_column($photos, 'topic_activity_id');
        $topic_infos = TopicActivity::getByIds($topic_ids);
        $topic_infos_regular = $topic_infos ? array_column($topic_infos, null, 'id') : [];
        //特征信息
        $features = AdmNoteFeature::getFeatureByIds($ids);
        $features_arr = [];
        if ($features && is_array($features)) {
            foreach ($features as $features_info) {
                $features_arr[$features_info['note_id']][] = $features_info['feature'];
            }
        }
        $features_regular = [];
        if ($features_arr && is_array($features_arr)) {
            foreach ($features_arr as $note_id => $feature) {
                $features_regular[$note_id] = implode(',', $feature);
                $features_regular[$note_id] = array_unique(explode(',', $features_regular[$note_id]));
                $features_regular[$note_id] = implode(',', $features_regular[$note_id]);
            }
        }

        $admin_comments = [];
        $comments = AdminAccountOperate::getByObjIds($ids);
        if ($comments && is_array($comments)) {
            foreach ($comments as $comment) {
                $admin_comments[$comment['obj_id']] = (string)Admin::user()->find($comment['admin_id'])->name;
            }
        }

        $admin_likes = [];
        $likes = AdminAccountOperate::getByObjIds($ids, AdminAccountOperate::ACCOUNT_TYPE_LIKE);
        if ($likes && is_array($likes)) {
            foreach ($likes as $like) {
                $admin_likes[$like['obj_id']] = (string)Admin::user()->find($like['admin_id'])->name;
            }
        }

        // 获取note关联的wiki
        $wiki_map = Photos::getWikiListMapByIds($ids);
        //获取扩展信息
        $extend_map = [];
        $extend_info = PhotosExtend::getExtendInfoByNoteIds($ids);
        if ($extend_info && is_array($extend_info)) {
            foreach ($extend_info as $value) {
                $extend_map[$value['obj_id']] = $value;
            }
        }

        $i = 1;
        foreach ($photos as &$info) {
            $info['photo_id'] = $info['id'];
            $info['id'] = $i;
            $info['user_info'] = $user_infos_regular[$info['uid']];
            $info['admin_comment'] = (string)$admin_comments[$info['photo_id']];
            $info['admin_like'] = (string)$admin_likes[$info['photo_id']];
            $info['topic_info'] = $topic_infos_regular[$info['topic_activity_id']];
            $info['features'] = $features_regular[$info['photo_id']];
            $info['user_levels'] = $user_levels[$info['uid']];
            if ($info['show_type'] == DbPhotos::SHOW_TYPE_VIDEO) {
                $videoInfo = sVideos::getVideoCoverInfoById($info['video_id']);
                $info['expand'] = $this->_getVideoExpand($videoInfo, $wiki_map[$info['photo_id']]['list']);
            } else {
                $picInfos = json_decode($info['pic_list'], true) ?: [];
                $info['expand'] = $this->_getPicExpand($picInfos, $wiki_map[$info['photo_id']]['list']);
            }
            $info['expand'] .= $this->_getDivLine();
            if ($info['type'] == dbPhoto::TYPE_DIARY) {
                $info['title'] = $diaryList[$info['photo_id']]['title'];
                $info['task_id'] = $diaryList[$info['photo_id']]['task_id'];
            }
            if ($info['type'] == dbPhoto::TYPE_CIRCLE) {
                $info['name'] = $circleList[$info['photo_id']]['circle_name'];
                $info['task_id'] = $circleList[$info['photo_id']]['circle_id'];
            }
            $i++;
        }

        $options = [
            'perPage' => $request->input('per_page') ?: 20
        ];
        $gridModel = new pGridDataModel($photos, $total, $options);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($result) {

            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->disableActions();
            $grid->expandFilter();

            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });
            });

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->dropDown('time', [
                    'add_time' => '入池时间',
                ])->betweenDatetime();
            });

            $grid->column('photo_id', 'NOTE_ID')->expand(function () {
                return $this->expand;
            }, true)->width(90);
            $grid->column('uid', '用户信息')->userBasicInfo()->width(150);
            $grid->column('admin_comment', '额外信息')->display(function () {
                $log = "<a href='/admin/photo/photoAuditLog?&id=$this->photo_id' target='_blank' >审核日志</a><br>";
                $copy_btn = "<a href='javascript:;' class='btn btn-default copyH5'  data-id='$this->photo_id' >复制链接</a>";

                return $log . "<br><br>" . $copy_btn;
            })->width(150);
            $grid->column('remark', '图说')->display(function () {
                $s2 = preg_replace("/#.*?\s/", '', $this->remark . $this->title);
                $s3 = preg_replace("/\\[.*?]/", '', $s2);
                $s4 = preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/", "", strip_tags($s3));
                return "<strong>[字数]: </strong>" .
                    mb_strlen($s4) . "<br><strong>[标题]:</strong>{$this->title}<br><strong>[正文]:</strong><br>" . str_replace(' ', '&nbsp;', nl2br($this->remark));
            })->width(350);

            $grid->column('relation', '关联信息')->display(function () use ($result) {
                $addtime = date('Y-m-d H:i:s', $this->addtime);
                $addPoolTime = date('Y-m-d H:i:s', $result[$this->photo_id]);
                $string = "";
                if ($this->topic_activity_id) {
                    if ($this->type == dbPhoto::TYPE_CIRCLE) {
                        $string .= "内容主体：<br>圈子内容 <br> 圈子id：{$this->task_id} <br> " .
                            "话题 <br>话题id：" . "<a href='http://manage.haohaozhu.me/Admin/Question/questionListNew/menuid/1012.html?id=$this->topic_activity_id' target='_blank' >" .
                            $this->topic_activity_id . "</a>" .
                            '<br>' . "话题标题：" .
                            $this->topic_info['title'] .
                            " <br> 圈子名称：{$this->name}";
                    } else {
                        $string .= "内容主体：话题 <br>话题id：" . "<a href='http://manage.haohaozhu.me/Admin/Question/questionListNew/menuid/1012.html?id=$this->topic_activity_id' target='_blank' >" . $this->topic_activity_id . "</a>" . '<br>' . "话题标题：" . $this->topic_info['title'];
                    }
                } else if ($this->type == dbPhoto::TYPE_DIARY) {
                    $string .= "内容主体：装修日记 <br> 日记id：{$this->task_id}";
                } else if ($this->type == dbPhoto::TYPE_CIRCLE) {
                    $string .= "内容主体：圈子内容 <br> 圈子id：{$this->task_id} <br> 圈子名称：{$this->name}";
                } else {
                    $string .= "内容主体：图片";
                }
                $string .= "<br>发布时间{$addtime} <br>入池时间 {$addPoolTime}";
                return $string;
            })->width(150);
            $grid->column('admin_score', '打分')->display(function () {
                $class_best = 'btn-defalut';
                if ($this->admin_score >= 80) {
                    $class_best = 'btn-success';
                }
                return  "<button class='btn best grade $class_best' data-note-id='$this->photo_id' data-score='80' data-quality='" . dbPhoto::QUALITY_FEATURED . "'>" . dbPhoto::QUALITY_DESC[dbPhoto::QUALITY_FEATURED] . "</button><br><br>";
            });
        });

        Admin::script($this->gradeScript());
        Admin::script($this->imgScript());
        Admin::script($this->adminCopy());
        return $content
            ->header('待精选池')
            ->row("<div style='position:fixed;z-index:10000;top:50px;left:35%;width:600px;height:600px;' class='imgMoveDiv'><img src='' alt='' class='imgMove' style='width:auto;height:auto;max-width:100%;max-height:100%;'></div>")
            ->body($listGrid);

    }

    public function adminCopy()
    {
        return <<<SCRIPT
        $('.copyH5').click(function() {
            var id = $(this).data('id');
            $.ajax({type:"get",url:"photocheck/copy/"+id,success:function(url){
            var tempInput = document.createElement("input");
            tempInput.value = url;
            document.body.appendChild(tempInput);
            tempInput.select();
            document.execCommand("copy");
            document.body.removeChild(tempInput);
            }});
        });
SCRIPT;
    }

    public function imgScript()
    {
        return <<<SCRIPT
            $('.imgMoveDiv').hide();
            $('.img').click(function() {
                $('.imgMove').attr('src', $(this).attr('src'));
                $('.imgMoveDiv').show();      
            });
            $('.imgMoveDiv').click(function() {
                $('.imgMoveDiv').hide();      
            });

SCRIPT;
    }

    private function gradeScript()
    {
        $url = route('photocheck.grade');
        return <<<SCRIPT
            $('.grade').click(function() {
                $(this).addClass('btn-success');
                $(this).siblings('button').removeClass('btn-success');
                $(this).siblings('button').addClass('btn-default');
                toastr.success('打分成功', null, {
                    timeOut : 1000
                });
                
                let noteId = $(this).data('note-id');
                let score = $(this).data('score');
                let quality = $(this).data('quality');
                let url = '{$url}'
                let params = {note_id:noteId, score:score, quality:quality, source:2}
                $.post(url, params)
            });

SCRIPT;
    }

    private function _getVideoExpand($videoInfo, $wikiInfos)
    {
        $row = new Row();
        $row->column(4, "<video class='img-responsive container-fluid' controls src='{$videoInfo['basicInfo']['play_url_for_frieza']}' ></video>");
        $content = "<img class='img-responsive float-left center-block col-md-2' src='{$videoInfo['basicInfo']['ori_pic_url']}' />";
        $content = $content . implode("", array_map(function ($snapshotImg) {
                return "<img class='img-responsive float-left center-block col-md-2' src='{$snapshotImg}' />";
            }, (array)$videoInfo['snapshot']));

        $row->column(8, $content);
        $box = new Box('视频信息');
        $box->solid()->content($row->render());
        return $box->render() . ($wikiInfos ? $this->_getWikiExpand($wikiInfos) : '');
    }

    private function _getPicExpand($picInfos, $wikiInfos)
    {
        $row = new Row();
        $row->column(12, implode("", array_map(function ($picInfo) {
            $imgUrl = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $picInfo['pic_id'], ImgUrl::IMAGE_SIZE_ORI_NPHONE);
            return "<img class='img-responsive float-left center-block col-md-2 img' src='{$imgUrl}' />";
        }, (array)$picInfos)));
        $box = new Box('图片信息' . '  (数量:' . count($picInfos) . ')');
        $box->solid()->content($row->render());
        return $box->render() . ($wikiInfos ? $this->_getWikiExpand($wikiInfos) : '');
    }

    private function _getWikiExpand($wikiInfos)
    {
        $row = new Row();
        $row->column(12, implode("", array_map(function ($wikiInfo) {
            return "<div style='display:inline-block;margin:3px;width:220px;height:220px;'>" .
                "<img src='" . $wikiInfo['cover_img'] . "' height='200' class='img' /><br/>" .
                "<a href='https://beerus.haohaozhu.me/admin/wiki/admList/{$wikiInfo['id']}/edit' target='_blank' >{$wikiInfo['basic_title']}</a>" .
                "</div>";

        }, (array)$wikiInfos)));
        $box = new Box('wiki信息');
        $box->solid()->content($row->render());
        return $box->render();
    }

    /**
     * 分割线
     * @return string
     */
    private function _getDivLine()
    {
        return "<div style='width:100%;height:5px;background-color:#4169E1;margin-bottom:20px;'></div>";
    }
}